package demos;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket {
    private int number = 40;
    private final Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        try {
            if (number > 0) System.out.println(Thread.currentThread().getName() + " is saling " + (number--) + ", left" + number );
        } catch (Exception e) { e.printStackTrace(); } finally {
            lock.unlock();
        }
    }
}

/**
 * 高内聚低耦合
 * 线程   操作  资源类
 */
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket tickets = new Ticket();
        new Thread(() -> {for (int i = 0; i < 40; ++i) tickets.sale();}, "AA").start();
        new Thread(() -> {for (int i = 0; i < 40; ++i) tickets.sale();}, "BB").start();
        new Thread(() -> {for (int i = 0; i < 40; ++i) tickets.sale();}, "CC").start();
    }
}
